<!-- 关联小程序 -->
<template>
	<uni-card spacing="0" :is-shadow="false" :border="false">
		<view class="item-dom">
			<view class="flex-row flex-row-space-between">
				<text class="title1">说明：</text>
			</view>
			<view style="padding:  0 10px;">
				<view>1，开启信息推送才能在微信服务通知里面查看到关于自己的通知</view>
				<view>2，开启信息推送的推送内容包括（活动通知，咨询通知）</view>
			</view>
		</view>
	</uni-card>
	<button @click="closeOK" v-if="userData.subscribe == 1" class="basicbutton1" hover-class="basicbutton1-hover">关闭消息推送</button>
	<button v-else open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" class="basicbutton"
		hover-class="basicbutton-hover">开启消息推送</button>
</template>

<script lang="ts" setup>
	import {setUser, getUser } from "@/utils/storage"
	import { User } from "@/api/tables/User"
	import { openMsgNotification, closeMsgNotification } from "@/api/user"
	import { ref , onBeforeMount} from 'vue'
	
	let userData = ref<User>({}) 
	onBeforeMount(() => {
		userData.value = getUser()
	})
	function decryptPhoneNumber(e) {
		if(!userData.value.phonenumber){
			uni.showModal({
				title: '提示',
				content: '个人消息中联系电话为空 请先到修改基本消息中填写联系电话',
				success(res) {
					if (res.confirm) {
					} else if (res.cancel) {
					}
				},
			});
			return 
		}
		if (e.detail.code) {
			uni.login({ //获取到用户信息
				provider: 'weixin',
				success: (res => {
					let encryptedTel = e.detail.code
					let jsCode = res.code
					openOk(encryptedTel, jsCode)
				}),
				fail: (err) => {
					uni.showToast({
						title: '授权失败取消',
						icon: 'error',
						mask: true,
					});
				}
			})
		}
	}
	
	// 开启消息推送确定
	function openOk(encryptedTel, jsCode) {
		openMsgNotification({
			encryptedTel,
			jsCode,
			userId: userData.value.userId,
			userType: userData.value.userType
		}).then(res => {
			if (res.code == '200') {
				let data = res.data || {}
				if(data.nickname){
					uni.showModal({
						title: '提示',
						content: data.nickname,
						showCancel: false,
					});
				}
				userData.value.subscribe = 1
				setUser(userData.value)
			}
		})
	}
	// 关闭消息推送 确定
	function closeOK(){
		closeMsgNotification({
			id: userData.value.id,
		}).then(res => {
			if (res.code == '200') {
				userData.value.subscribe = 0
				setUser(userData.value)
			}
		})
	}
	
</script>

<style lang="scss" scoped>
	.item-dom {
		font-size: 28rpx;
		color: #999999;
		font-family: "微软雅黑";

		.title1 {
			font-size: 26rpx;
			line-height: 2;
			font-weight: 600;
			color: #01c2b7;
		}
	}
	.basicbutton, .basicbutton1{
		margin: 0  15px;
	}
</style>